const fs = require("fs");
const path = require("path");
const mm = require("mmmagic");

// 文件类型检测
const detectMimeType = (filePath) => {
  return new Promise((resolve, reject) => {
    const magic = new mm.Magic(mm.MAGIC_MIME_TYPE);
    magic.detectFile(filePath, (err, result) => {
      if (err) return reject(err);
      resolve(result);
    });
  });
};

// 验证文件是否是图片
const validateImage = async (file) => {
  // 1. 文件扩展名验证
  const ext = path.extname(file.filename).toLowerCase();
  const allowedExtensions = [".jpg", ".jpeg", ".png", ".gif", ".webp"];
  if (!allowedExtensions.includes(ext)) {
    throw new Error("不支持的文件类型");
  }

  // 2. MIME类型验证
  const mimeType = await detectMimeType(file.filepath);
  const allowedMimes = ["image/jpeg", "image/png", "image/gif", "image/webp"];

  if (!allowedMimes.includes(mimeType)) {
    throw new Error("文件内容类型不匹配");
  }

  // 3. 文件大小验证
  const stats = fs.statSync(file.filepath);
  const maxSize = 2 * 1024 * 1024; // 2MB
  if (stats.size > maxSize) {
    throw new Error("文件大小超过2MB限制");
  }

  // 4. 防止空文件
  if (stats.size === 0) {
    throw new Error("文件内容为空");
  }

  return true;
};

module.exports = {
  validateImage,
};
